#include "utils.h"
#include <sstream>
#include <fstream>
#include <algorithm>
#include <unistd.h>
#include <pwd.h>

std::vector<std::string> Utils::split(const std::string& str, char delimiter) {
    std::vector<std::string> tokens;
    std::stringstream ss(str);
    std::string token;
    
    while (std::getline(ss, token, delimiter)) {
        tokens.push_back(token);
    }
    
    return tokens;
}

std::string Utils::trim(const std::string& str) {
    const std::string whitespace = " \t\n\r\f\v";
    size_t start = str.find_first_not_of(whitespace);
    
    if (start == std::string::npos) {
        return ""; // 字符串全为空白字符
    }
    
    size_t end = str.find_last_not_of(whitespace);
    return str.substr(start, end - start + 1);
}

bool Utils::file_exists(const std::string& path) {
    std::ifstream file(path);
    return file.good();
}

std::string Utils::read_file(const std::string& path) {
    std::ifstream file(path);
    std::stringstream buffer;
    
    if (file.is_open()) {
        buffer << file.rdbuf();
        file.close();
    }
    
    return buffer.str();
}

std::string Utils::get_username(uid_t uid) {
    struct passwd* pwd = getpwuid(uid);
    if (pwd) {
        return std::string(pwd->pw_name);
    }
    return "unknown";
}

double Utils::get_system_uptime() {
    std::string uptime_str = read_file("/proc/uptime");
    if (!uptime_str.empty()) {
        std::istringstream iss(uptime_str);
        double uptime;
        if (iss >> uptime) {
            return uptime;
        }
    }
    return 0.0;
}